package me.thinkjet.sso.server.ticket;

import me.thinkjet.sso.server.authentication.Authentication;
import me.thinkjet.sso.server.service.CookieService;

/**
 * 
 * @ClassName TicketGrantingTicket
 * @author johnny_zyc
 * @Modified 2013-3-2 下午2:49:02
 * 
 */
public final class TicketGrantingTicket extends AbstractTicket {
	public static String PREFIX = "TGT";
	public final static String COOKIE_NAME = "TGC";
	public static long Cookie_Expired_Time = 86400; // Seconds of 1 days;

	private static final long serialVersionUID = -5197946718924166491L;

	private Authentication authentication;

	public TicketGrantingTicket() {
	}

	public TicketGrantingTicket(final String id,
			final TicketGrantingTicket ticketGrantingTicket,
			final Authentication authentication, final boolean rememberMe) {
		super(id, ticketGrantingTicket);
		this.authentication = authentication;
		if (rememberMe) {
			Cookie_Expired_Time = CookieService.REMEBER_ME_MAX_AGE;
		}
	}

	public TicketGrantingTicket(final String id,
			final Authentication authentication, final boolean rememberMe) {
		this(id, null, authentication, rememberMe);
	}

	public Authentication getAuthentication() {
		return this.authentication;
	}

	public synchronized ServiceTicket grantServiceTicket(final String id,
			final String service, final boolean credentialsProvided) {
		final ServiceTicket serviceTicket = new ServiceTicket(id, this,
				service, this.getCountOfUses() == 0 || credentialsProvided);
		updateState();
		return serviceTicket;
	}

	public boolean isRoot() {
		return this.getGrantingTicket() == null;
	}

	public final boolean isExpired() {
		return (System.currentTimeMillis() - this.getLastTimeUsed() > TicketGrantingTicket.Cookie_Expired_Time * 1000)
				|| (getGrantingTicket() != null && getGrantingTicket()
						.isExpired()) || isExpiredInternal();
	}

}
